using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using SvgToFontConverter.Models;

namespace SvgToFontConverter.Services
{
    /// <summary>
    /// SVG2TTF服务类，负责SVG到字体的转换
    /// 使用专业的SVG处理服务和相同的缩放逻辑
    /// </summary>
    public class Svg2TtfService
    {
        private readonly SvgProcessorService _svgProcessor;
        
        public Svg2TtfService()
        {
            _svgProcessor = new SvgProcessorService();
        }
        
        /// <summary>
        /// 将SVG文件转换为TTF字体
        /// </summary>
        /// <param name="svgFiles">SVG文件路径列表</param>
        /// <param name="outputPath">输出TTF文件路径</param>
        /// <param name="fileName">输出文件名（可能包含批次后缀）</param>
        /// <param name="config">SVG2TTF配置</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <param name="fontName">字体内部名称（不包含批次后缀）</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <param name="fontAuthor">字体作者</param>
        /// <param name="fontVersion">字体版本</param>
        /// <returns>转换是否成功</returns>
        public async Task<bool> ConvertSvgToTtfAsync(List<string> svgFiles, string outputPath, 
            string fileName, Svg2TtfConfig config, CancellationToken cancellationToken = default,
            string fontName = null, string fontFamily = null, string fontAuthor = null, string fontVersion = null)
        {
            try
            {
                // 设置字体属性
                var actualFontName = fontName ?? "CustomFont";
                var actualFontFamily = fontFamily ?? "CustomFont";
                var actualFontAuthor = fontAuthor ?? "Unknown";
                var actualFontVersion = fontVersion ?? "1.0";
                
                Debug.WriteLine($"开始SVG2TTF转换，文件数量: {svgFiles.Count}");
                Debug.WriteLine($"输出路径: {outputPath}");
                Debug.WriteLine($"字体名称: {actualFontName}");
                Debug.WriteLine($"字体族名称: {actualFontFamily}");
                
                if (svgFiles == null || svgFiles.Count == 0)
                {
                    Debug.WriteLine("错误: 没有提供SVG文件");
                    return false;
                }
                
                // 验证Node.js和SVG2TTF是否可用
                if (!await ValidateEnvironmentAsync(config))
                {
                    Debug.WriteLine("错误: SVG2TTF环境验证失败");
                    return false;
                }
                
                // 创建临时工作目录
                var tempDir = Path.Combine(Path.GetTempPath(), $"svg2ttf_{Guid.NewGuid():N}");
                Directory.CreateDirectory(tempDir);
                
                try
                {
                    // 处理每个SVG文件
                    var processedSvgs = new List<string>();
                    
                    foreach (var svgFile in svgFiles)
                    {
                        if (cancellationToken.IsCancellationRequested)
                            return false;
                            
                        var processedSvg = await ProcessSvgFileAsync(svgFile, tempDir);
                        if (!string.IsNullOrEmpty(processedSvg))
                        {
                            processedSvgs.Add(processedSvg);
                        }
                    }
                    
                    if (processedSvgs.Count == 0)
                    {
                        Debug.WriteLine("错误: 没有成功处理的SVG文件");
                        return false;
                    }
                    
                    // 使用SVG2TTF转换为TTF
                    return await ConvertToTtfAsync(processedSvgs, outputPath, actualFontName, actualFontFamily, config, cancellationToken);
                }
                finally
                {
                    // 清理临时目录
                    try
                    {
                        if (Directory.Exists(tempDir))
                        {
                            Directory.Delete(tempDir, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"清理临时目录失败: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"SVG2TTF转换失败: {ex.Message}");
                Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return false;
            }
        }
        
        /// <summary>
        /// 验证SVG2TTF环境
        /// </summary>
        /// <param name="config">配置</param>
        /// <returns>是否验证成功</returns>
        private async Task<bool> ValidateEnvironmentAsync(Svg2TtfConfig config)
        {
            try
            {
                // 验证Node.js
                var nodeJsPath = string.IsNullOrEmpty(config.NodeJsPath) ? "node" : Path.Combine(config.NodeJsPath, "node.exe");
                var nodeProcess = new ProcessStartInfo
                {
                    FileName = nodeJsPath,
                    Arguments = "--version",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };
                
                // 继承当前进程的环境变量，确保PATH正确设置
                foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                {
                    nodeProcess.EnvironmentVariables[env.Key.ToString()] = env.Value.ToString();
                }
                
                using (var process = Process.Start(nodeProcess))
                {
                    if (process == null)
                    {
                        Debug.WriteLine("无法启动Node.js进程");
                        return false;
                    }
                    
                    var outputTask = process.StandardOutput.ReadToEndAsync();
                    var errorTask = process.StandardError.ReadToEndAsync();
                    
                    process.WaitForExit();
                    
                    var nodeVersion = await outputTask;
                    var error = await errorTask;
                    
                    if (process.ExitCode != 0)
                    {
                        Debug.WriteLine($"Node.js验证失败，退出码: {process.ExitCode}");
                        Debug.WriteLine($"错误信息: {error}");
                        return false;
                    }
                    
                    Debug.WriteLine($"Node.js版本: {nodeVersion.Trim()}");
                }
                
                // 验证SVG2TTF CLI
                var svg2ttfProcess = new ProcessStartInfo
                {
                    FileName = nodeJsPath,
                    Arguments = "-e \"console.log(require('svg2ttf').toString())\"",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };
                
                // 继承当前进程的环境变量，确保PATH正确设置
                foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                {
                    svg2ttfProcess.EnvironmentVariables[env.Key.ToString()] = env.Value.ToString();
                }
                
                // 设置NODE_PATH以确保能找到全局模块
                try
                {
                    var npmRootProcess = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = "/c npm root -g",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    };
                    
                    using (var npmProcess = Process.Start(npmRootProcess))
                    {
                        if (npmProcess != null)
                        {
                            npmProcess.WaitForExit();
                            if (npmProcess.ExitCode == 0)
                            {
                                var output = npmProcess.StandardOutput.ReadToEnd().Trim();
                                if (!string.IsNullOrEmpty(output))
                                {
                                    // npm root -g 可能输出多行，取最后一行作为实际路径
                                    var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                    var globalNodeModules = lines.Length > 0 ? lines[lines.Length - 1].Trim() : output;
                                    
                                    if (!string.IsNullOrEmpty(globalNodeModules))
                                    {
                                        svg2ttfProcess.EnvironmentVariables["NODE_PATH"] = globalNodeModules;
                                        Debug.WriteLine($"验证时设置NODE_PATH: {globalNodeModules}");
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"验证时获取npm全局路径失败: {ex.Message}");
                }
                
                using (var process = Process.Start(svg2ttfProcess))
                {
                    if (process == null)
                    {
                        Debug.WriteLine("无法验证SVG2TTF模块");
                        return false;
                    }
                    
                    var outputTask = process.StandardOutput.ReadToEndAsync();
                    var errorTask = process.StandardError.ReadToEndAsync();
                    
                    process.WaitForExit();
                    
                    var output = await outputTask;
                    var error = await errorTask;
                    
                    if (process.ExitCode != 0)
                    {
                        Debug.WriteLine($"SVG2TTF模块验证失败: {error}");
                        Debug.WriteLine("请确保已安装SVG2TTF: npm install -g svg2ttf");
                        return false;
                    }
                    
                    Debug.WriteLine("SVG2TTF模块验证成功");
                    Debug.WriteLine($"SVG2TTF输出: {output.Trim()}");
                }
                
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"环境验证失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 处理单个SVG文件
        /// </summary>
        /// <param name="svgFile">SVG文件路径</param>
        /// <param name="tempDir">临时目录</param>
        /// <returns>处理后的SVG文件路径</returns>
        private Task<string> ProcessSvgFileAsync(string svgFile, string tempDir)
        {
            try
            {
                var fileName = Path.GetFileNameWithoutExtension(svgFile);
                Debug.WriteLine($"\n=== 处理文件: {fileName} ===");
                
                if (!File.Exists(svgFile))
                {
                    Debug.WriteLine($"文件不存在: {svgFile}");
                    return Task.FromResult<string>(null);
                }
                
                // 读取原始SVG内容
                var originalSvgContent = File.ReadAllText(svgFile);
                Debug.WriteLine($"SVG内容长度: {originalSvgContent.Length}");
                
                // 直接提取SVG路径数据，不应用transform修正（避免字符上下颠倒）
                var processedPath = ExtractPathDataDirectly(originalSvgContent);
                if (string.IsNullOrEmpty(processedPath))
                {
                    Debug.WriteLine($"警告: 文件 {fileName} 无法提取有效的SVG路径");
                    return Task.FromResult<string>(null);
                }
                
                Debug.WriteLine($"处理后的路径: {processedPath}");
                
                // 计算实际字符宽度（使用与SvgProcessorService相同的逻辑）
                var actualCharWidth = CalculateCharacterWidth(originalSvgContent);
                Debug.WriteLine($"实际字符宽度: {actualCharWidth:F2}");
                
                // 创建优化的SVG内容
                var optimizedSvgContent = CreateOptimizedSvg(processedPath, actualCharWidth);
                
                // 保存处理后的SVG文件
                var outputSvgPath = Path.Combine(tempDir, $"{fileName}.svg");
                File.WriteAllText(outputSvgPath, optimizedSvgContent);
                
                Debug.WriteLine($"成功处理文件: {fileName}");
                return Task.FromResult(outputSvgPath);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"处理文件 {svgFile} 时发生错误: {ex.Message}");
                return Task.FromResult<string>(null);
            }
        }
        
        /// <summary>
        /// 直接提取SVG路径数据，应用transform变换但不进行垂直翻转修正
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <returns>路径数据</returns>
        private string ExtractPathDataDirectly(string svgContent)
        {
            try
            {
                var pathBuilder = new StringBuilder();
                
                // 首先查找所有的g元素及其transform属性
                var gPattern = @"<g[^>]*transform\s*=\s*[""']([^""']*)[""'][^>]*>([\s\S]*?)</g>";
                var gMatches = System.Text.RegularExpressions.Regex.Matches(svgContent, gPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                
                if (gMatches.Count > 0)
                {
                    Debug.WriteLine($"检测到{gMatches.Count}个带transform的g元素");
                    
                    foreach (System.Text.RegularExpressions.Match gMatch in gMatches)
                    {
                        var transformAttr = gMatch.Groups[1].Value;
                        var gContent = gMatch.Groups[2].Value;
                        
                        // 解析transform属性中的translate和scale值
                        double translateX = 0, translateY = 0;
                        double scaleX = 1, scaleY = 1;
                        
                        var translateMatch = System.Text.RegularExpressions.Regex.Match(transformAttr, @"translate\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        if (translateMatch.Success)
                        {
                            double.TryParse(translateMatch.Groups[1].Value, out translateX);
                            if (translateMatch.Groups[2].Success && !string.IsNullOrEmpty(translateMatch.Groups[2].Value))
                            {
                                double.TryParse(translateMatch.Groups[2].Value, out translateY);
                            }
                        }
                        
                        var scaleMatch = System.Text.RegularExpressions.Regex.Match(transformAttr, @"scale\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        if (scaleMatch.Success)
                        {
                            double.TryParse(scaleMatch.Groups[1].Value, out scaleX);
                            if (scaleMatch.Groups[2].Success && !string.IsNullOrEmpty(scaleMatch.Groups[2].Value))
                            {
                                double.TryParse(scaleMatch.Groups[2].Value, out scaleY);
                            }
                            else
                            {
                                scaleY = scaleX; // 如果只有一个值，X和Y使用相同的缩放
                            }
                        }
                        
                        Debug.WriteLine($"解析transform - translate: x={translateX}, y={translateY}, scale: x={scaleX}, y={scaleY}");
                        
                        // 在g元素内容中查找path元素
                        var pathPattern = @"<path[^>]*d\s*=\s*[""']([^""']*)[""'][^>]*>";
                        var pathMatches = System.Text.RegularExpressions.Regex.Matches(gContent, pathPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        
                        foreach (System.Text.RegularExpressions.Match pathMatch in pathMatches)
                        {
                            if (pathMatch.Groups.Count > 1)
                            {
                                var pathData = pathMatch.Groups[1].Value.Trim();
                                if (!string.IsNullOrEmpty(pathData))
                                {
                                    // 应用transform变换到路径数据，但不进行垂直翻转修正
                                    var transformedPath = ApplyTransformToPathSimple(pathData, translateX, translateY, scaleX, scaleY);
                                    pathBuilder.Append(transformedPath).Append(" ");
                                    Debug.WriteLine($"应用transform后的路径数据: {transformedPath}");
                                }
                            }
                        }
                    }
                }
                else
                {
                    // 普通SVG：提取所有path元素
                    Debug.WriteLine("检测到普通SVG，提取所有路径数据");
                    var pathPattern = @"<path[^>]*d\s*=\s*[""']([^""']*)[""'][^>]*>";
                    var pathMatches = System.Text.RegularExpressions.Regex.Matches(svgContent, pathPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    
                    foreach (System.Text.RegularExpressions.Match match in pathMatches)
                    {
                        if (match.Groups.Count > 1)
                        {
                            var pathData = match.Groups[1].Value.Trim();
                            if (!string.IsNullOrEmpty(pathData))
                            {
                                pathBuilder.Append(pathData).Append(" ");
                                Debug.WriteLine($"提取路径数据: {pathData}");
                            }
                        }
                    }
                }
                
                var result = pathBuilder.ToString().Trim();
                return string.IsNullOrEmpty(result) ? "M100 100h800v800h-800z" : result; // 默认矩形路径
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"提取路径数据失败: {ex.Message}");
                return "M100 100h800v800h-800z"; // 默认矩形路径
            }
        }
        
        /// <summary>
        /// 应用transform变换到路径数据，包含垂直翻转修正
        /// </summary>
        /// <param name="pathData">原始路径数据</param>
        /// <param name="translateX">X轴平移</param>
        /// <param name="translateY">Y轴平移</param>
        /// <param name="scaleX">X轴缩放</param>
        /// <param name="scaleY">Y轴缩放</param>
        /// <returns>变换后的路径数据</returns>
        private string ApplyTransformToPathSimple(string pathData, double translateX, double translateY, double scaleX, double scaleY)
        {
            try
            {
                // 字体坐标系需要垂直翻转修正
                const double fontHeight = 1000.0; // 字体单位高度
                
                // 使用正则表达式解析路径命令和坐标
                var result = System.Text.RegularExpressions.Regex.Replace(pathData, @"([MLHVCSQTAZ])([^MLHVCSQTAZ]*)", 
                    match =>
                    {
                        var command = match.Groups[1].Value;
                        var coords = match.Groups[2].Value;
                        
                        if (string.IsNullOrWhiteSpace(coords))
                        {
                            return command;
                        }
                        
                        var numbers = System.Text.RegularExpressions.Regex.Matches(coords, @"-?\d+(?:\.\d+)?")
                            .Cast<System.Text.RegularExpressions.Match>()
                            .Select(m => double.Parse(m.Value))
                            .ToArray();
                        
                        if (numbers.Length == 0)
                        {
                            return match.Value;
                        }
                        
                        var transformedNumbers = new List<double>();
                        var upperCommand = command.ToUpper();
                        
                        switch (upperCommand)
                        {
                            case "M": // MoveTo
                            case "L": // LineTo
                                for (int i = 0; i < numbers.Length; i += 2)
                                {
                                    if (i + 1 < numbers.Length)
                                    {
                                        var x = numbers[i] * scaleX + translateX;
                                        var y = numbers[i + 1] * scaleY + translateY;
                                        // 垂直翻转修正
                                        y = fontHeight - y;
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                            case "H": // Horizontal LineTo
                                for (int i = 0; i < numbers.Length; i++)
                                {
                                    transformedNumbers.Add(numbers[i] * scaleX + translateX);
                                }
                                break;
                            case "V": // Vertical LineTo
                                for (int i = 0; i < numbers.Length; i++)
                                {
                                    var y = numbers[i] * scaleY + translateY;
                                    // 垂直翻转修正
                                    y = fontHeight - y;
                                    transformedNumbers.Add(y);
                                }
                                break;
                            case "C": // CurveTo
                                for (int i = 0; i < numbers.Length; i += 6)
                                {
                                    if (i + 5 < numbers.Length)
                                    {
                                        var x1 = numbers[i] * scaleX + translateX;
                                        var y1 = numbers[i + 1] * scaleY + translateY;
                                        var x2 = numbers[i + 2] * scaleX + translateX;
                                        var y2 = numbers[i + 3] * scaleY + translateY;
                                        var x = numbers[i + 4] * scaleX + translateX;
                                        var y = numbers[i + 5] * scaleY + translateY;
                                        
                                        // 垂直翻转修正
                                        y1 = fontHeight - y1;
                                        y2 = fontHeight - y2;
                                        y = fontHeight - y;
                                        
                                        transformedNumbers.Add(x1);
                                        transformedNumbers.Add(y1);
                                        transformedNumbers.Add(x2);
                                        transformedNumbers.Add(y2);
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                            case "Q": // QuadraticCurveTo
                                for (int i = 0; i < numbers.Length; i += 4)
                                {
                                    if (i + 3 < numbers.Length)
                                    {
                                        var x1 = numbers[i] * scaleX + translateX;
                                        var y1 = numbers[i + 1] * scaleY + translateY;
                                        var x = numbers[i + 2] * scaleX + translateX;
                                        var y = numbers[i + 3] * scaleY + translateY;
                                        
                                        // 垂直翻转修正
                                        y1 = fontHeight - y1;
                                        y = fontHeight - y;
                                        
                                        transformedNumbers.Add(x1);
                                        transformedNumbers.Add(y1);
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                            case "Z": // ClosePath
                                return command;
                            default:
                                // 对于其他命令，简单地应用变换
                                for (int i = 0; i < numbers.Length; i += 2)
                                {
                                    if (i + 1 < numbers.Length)
                                    {
                                        var x = numbers[i] * scaleX + translateX;
                                        var y = numbers[i + 1] * scaleY + translateY;
                                        // 垂直翻转修正
                                        y = fontHeight - y;
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                        }
                        
                        return command + string.Join(",", transformedNumbers.Select(n => n.ToString("F2")));
                    }, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                
                return result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"应用transform变换失败: {ex.Message}");
                return pathData; // 返回原始路径数据
            }
        }
        
        /// <summary>
        /// 计算字符宽度（使用与SvgProcessorService相同的逻辑）
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <returns>实际字符宽度</returns>
        private double CalculateCharacterWidth(string svgContent)
        {
            try
            {
                // 解析viewBox
                var viewBoxMatch = System.Text.RegularExpressions.Regex.Match(svgContent, 
                    @"viewBox\s*=\s*[""']([^""']*)[""']", 
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    
                double sourceWidth = 100, sourceHeight = 100;
                
                if (viewBoxMatch.Success)
                {
                    var viewBoxValues = viewBoxMatch.Groups[1].Value.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (viewBoxValues.Length >= 4)
                    {
                        double.TryParse(viewBoxValues[2], out sourceWidth);
                        double.TryParse(viewBoxValues[3], out sourceHeight);
                    }
                }
                else
                {
                    // 如果没有viewBox，尝试解析width和height属性
                    var widthMatch = System.Text.RegularExpressions.Regex.Match(svgContent, 
                        @"width\s*=\s*[""']([^""']*)[""']", 
                        System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    var heightMatch = System.Text.RegularExpressions.Regex.Match(svgContent, 
                        @"height\s*=\s*[""']([^""']*)[""']", 
                        System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    
                    if (widthMatch.Success && heightMatch.Success)
                    {
                        var widthStr = widthMatch.Groups[1].Value.Replace("px", "").Replace("pt", "");
                        var heightStr = heightMatch.Groups[1].Value.Replace("px", "").Replace("pt", "");
                        double.TryParse(widthStr, out sourceWidth);
                        double.TryParse(heightStr, out sourceHeight);
                    }
                }
                
                // 使用与SvgProcessorService相同的缩放逻辑
                double targetCharHeight = 750.0;  // 固定高度750单位
                double scale = targetCharHeight / sourceHeight;
                
                // 确保最小缩放比例
                double minScale = Math.Min(targetCharHeight / sourceHeight, (1000 * 0.5) / Math.Max(sourceWidth, sourceHeight));
                if (scale < minScale)
                {
                    scale = minScale;
                }
                
                // 限制最大缩放比例
                if (scale > 20.0)
                {
                    scale = 20.0;
                }
                
                // 计算实际字符宽度
                return sourceWidth * scale;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"计算字符宽度失败: {ex.Message}");
                return 1000; // 默认宽度
            }
        }
        
        /// <summary>
        /// 创建优化的SVG内容
        /// </summary>
        /// <param name="pathData">路径数据</param>
        /// <param name="width">字符宽度</param>
        /// <returns>优化的SVG内容</returns>
        private string CreateOptimizedSvg(string pathData, double width)
        {
            var svgContent = new StringBuilder();
            svgContent.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            
            // 为了确保右线位置正确，viewBox宽度应该稍大于字符宽度
            // 添加一些边距，确保右线在字符右侧合适位置
            var viewBoxWidth = Math.Max(width + 100, 1000); // 至少1000单位宽度，或字符宽度+100边距
            
            svgContent.AppendLine($"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {viewBoxWidth:F0} 1000\" width=\"{viewBoxWidth:F0}\" height=\"1000\">");
            svgContent.AppendLine($"  <path d=\"{pathData}\" fill=\"currentColor\"/>");
            svgContent.AppendLine("</svg>");
            
            return svgContent.ToString();
        }
        
        /// <summary>
        /// 使用SVG2TTF转换为TTF字体
        /// </summary>
        /// <param name="svgFiles">处理后的SVG文件列表</param>
        /// <param name="outputPath">输出TTF文件路径</param>
        /// <param name="fontName">字体内部名称</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <param name="config">配置</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>转换是否成功</returns>
        private async Task<bool> ConvertToTtfAsync(List<string> svgFiles, string outputPath, 
            string fontName, string fontFamily, Svg2TtfConfig config, CancellationToken cancellationToken)
        {
            try
            {
                Debug.WriteLine($"开始转换为TTF，SVG文件数量: {svgFiles.Count}");
                
                // 创建转换脚本
                var scriptContent = CreateConversionScript(svgFiles, outputPath, fontName, fontFamily);
                var scriptPath = Path.Combine(Path.GetTempPath(), $"svg2ttf_script_{Guid.NewGuid():N}.js");
                
                File.WriteAllText(scriptPath, scriptContent);
                
                try
                {
                    // 执行转换脚本
                    var nodeJsPath = string.IsNullOrEmpty(config.NodeJsPath) ? "node" : Path.Combine(config.NodeJsPath, "node.exe");
                    var processInfo = new ProcessStartInfo
                    {
                        FileName = nodeJsPath,
                        Arguments = $"\"{scriptPath}\"",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        WorkingDirectory = Path.GetDirectoryName(outputPath)
                    };
                    
                    // 继承当前进程的环境变量，确保PATH正确设置
                    foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                    {
                        processInfo.EnvironmentVariables[env.Key.ToString()] = env.Value.ToString();
                    }
                    
                    // 设置NODE_PATH以确保能找到全局模块
                    try
                    {
                        var npmRootProcess = new ProcessStartInfo
                        {
                            FileName = "cmd.exe",
                            Arguments = "/c npm root -g",
                            UseShellExecute = false,
                            RedirectStandardOutput = true,
                            RedirectStandardError = true,
                            CreateNoWindow = true
                        };
                        
                        using (var npmProcess = Process.Start(npmRootProcess))
                        {
                            if (npmProcess != null)
                            {
                                npmProcess.WaitForExit();
                                if (npmProcess.ExitCode == 0)
                                {
                                    var output = npmProcess.StandardOutput.ReadToEnd().Trim();
                                    if (!string.IsNullOrEmpty(output))
                                    {
                                        // npm root -g 可能输出多行，取最后一行作为实际路径
                                        var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                        var globalNodeModules = lines.Length > 0 ? lines[lines.Length - 1].Trim() : output;
                                        
                                        if (!string.IsNullOrEmpty(globalNodeModules))
                                        {
                                            processInfo.EnvironmentVariables["NODE_PATH"] = globalNodeModules;
                                            Debug.WriteLine($"设置NODE_PATH: {globalNodeModules}");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"获取npm全局路径失败: {ex.Message}");
                    }
                    
                    using (var process = Process.Start(processInfo))
                    {
                        if (process == null)
                        {
                            Debug.WriteLine("无法启动SVG2TTF转换进程");
                            return false;
                        }
                        
                        // 等待进程完成或取消
                        while (!process.HasExited)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                process.Kill();
                                return false;
                            }
                            await Task.Delay(100, cancellationToken);
                        }
                        
                        var output = await process.StandardOutput.ReadToEndAsync();
                        var error = await process.StandardError.ReadToEndAsync();
                        
                        Debug.WriteLine($"SVG2TTF输出: {output}");
                        if (!string.IsNullOrEmpty(error))
                        {
                            Debug.WriteLine($"SVG2TTF错误: {error}");
                        }
                        
                        if (process.ExitCode == 0)
                        {
                            Debug.WriteLine($"SVG2TTF转换成功，输出文件: {outputPath}");
                            return File.Exists(outputPath);
                        }
                        else
                        {
                            Debug.WriteLine($"SVG2TTF转换失败，退出码: {process.ExitCode}");
                            return false;
                        }
                    }
                }
                finally
                {
                    // 清理脚本文件
                    try
                    {
                        if (File.Exists(scriptPath))
                        {
                            File.Delete(scriptPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"清理脚本文件失败: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"SVG2TTF转换失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 创建SVG2TTF转换脚本
        /// </summary>
        /// <param name="svgFiles">SVG文件列表</param>
        /// <param name="outputPath">输出路径</param>
        /// <param name="fontName">字体内部名称</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <returns>脚本内容</returns>
        private string CreateConversionScript(List<string> svgFiles, string outputPath, string fontName, string fontFamily)
        {
            var script = new StringBuilder();
            script.AppendLine("const fs = require('fs');");
            script.AppendLine("const path = require('path');");
            script.AppendLine("const svg2ttf = require('svg2ttf');");
            script.AppendLine();
            script.AppendLine("try {");
            script.AppendLine("  console.log('开始SVG2TTF转换...');");
            script.AppendLine();
            script.AppendLine("  // 创建SVG字体内容");
            script.AppendLine("  let svgFont = '<?xml version=\"1.0\" standalone=\"no\"?>\\n';");
            script.AppendLine("  svgFont += '<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\\n';");
            script.AppendLine($"  svgFont += '<svg xmlns=\"http://www.w3.org/2000/svg\">\\n';");
            script.AppendLine($"  svgFont += '<defs>\\n';");
            script.AppendLine($"  svgFont += '<font id=\"{fontName}\" horiz-adv-x=\"1000\">\\n';");
            script.AppendLine($"  svgFont += '<font-face font-family=\"{fontFamily}\" units-per-em=\"1000\" ascent=\"200\" descent=\"-800\" />\\n';");
            script.AppendLine("  svgFont += '<missing-glyph horiz-adv-x=\"500\" />\\n';");
            script.AppendLine();
            
            // 为每个SVG文件添加字形
            int unicode = 0xE000; // 私有使用区域起始
            int index = 0; // 使用索引作为变量名后缀
            foreach (var svgFile in svgFiles)
            {
                var fileName = Path.GetFileNameWithoutExtension(svgFile);
                script.AppendLine($"  // 处理文件: {fileName}");
                script.AppendLine($"  const svgContent{index} = fs.readFileSync('{svgFile.Replace("\\", "/")}', 'utf8');");
                script.AppendLine($"  const pathMatch{index} = svgContent{index}.match(/<path[^>]*d\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>/i);");
                script.AppendLine($"  if (pathMatch{index}) {{");
                script.AppendLine($"    let pathData{index} = pathMatch{index}[1];");
                script.AppendLine($"    ");
                script.AppendLine($"    // 检查是否有Y轴翻转的transform");
                script.AppendLine($"    // 处理g元素的transform变换");
                script.AppendLine($"    const gMatches{index} = svgContent{index}.match(/<g[^>]*transform\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>([\\s\\S]*?)<\\/g>/gi);");
                script.AppendLine($"    if (gMatches{index}) {{");
                script.AppendLine($"      gMatches{index}.forEach(gMatch => {{");
                script.AppendLine($"        const transformMatch = gMatch.match(/transform\\s*=\\s*[\"']([^\"']*)[\"']/i);");
                script.AppendLine($"        if (transformMatch && transformMatch[1]) {{");
                script.AppendLine($"          const transformAttr = transformMatch[1];");
                script.AppendLine($"          ");
                script.AppendLine($"          // 解析translate变换");
                script.AppendLine($"          let translateX = 0, translateY = 0;");
                script.AppendLine($"          const translateMatch = transformAttr.match(/translate\\s*\\(\\s*([^,\\s]+)\\s*,?\\s*([^\\)\\s]*)\\s*\\)/i);");
                script.AppendLine($"          if (translateMatch) {{");
                script.AppendLine($"            translateX = parseFloat(translateMatch[1]) || 0;");
                script.AppendLine($"            translateY = parseFloat(translateMatch[2]) || 0;");
                script.AppendLine($"          }}");
                script.AppendLine($"          ");
                script.AppendLine($"          // 解析scale变换");
                script.AppendLine($"          let scaleX = 1, scaleY = 1;");
                script.AppendLine($"          const scaleMatch = transformAttr.match(/scale\\s*\\(\\s*([^,\\s]+)\\s*,?\\s*([^\\)\\s]*)\\s*\\)/i);");
                script.AppendLine($"          if (scaleMatch) {{");
                script.AppendLine($"            scaleX = parseFloat(scaleMatch[1]) || 1;");
                script.AppendLine($"            scaleY = scaleMatch[2] ? parseFloat(scaleMatch[2]) : scaleX;");
                script.AppendLine($"          }}");
                script.AppendLine($"          ");
                script.AppendLine($"          console.log('Transform - translate:', translateX, translateY, 'scale:', scaleX, scaleY);");
                script.AppendLine($"          ");
                script.AppendLine($"          // 提取g元素内的path数据并应用变换");
                script.AppendLine($"          const gContent = gMatch.match(/<g[^>]*>([\\s\\S]*?)<\\/g>/i);");
                script.AppendLine($"          if (gContent && gContent[1]) {{");
                script.AppendLine($"            const pathMatches = gContent[1].match(/<path[^>]*d\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>/gi);");
                script.AppendLine($"            if (pathMatches) {{");
                script.AppendLine($"              pathMatches.forEach(pathMatch => {{");
                script.AppendLine($"                const pathDataMatch = pathMatch.match(/d\\s*=\\s*[\"']([^\"']*)[\"']/i);");
                script.AppendLine($"                if (pathDataMatch && pathDataMatch[1]) {{");
                script.AppendLine($"                  let transformedPath = pathDataMatch[1];");
                script.AppendLine($"                  ");
                script.AppendLine($"                  // 应用变换到路径数据（使用与SvgProcessorService相同的逻辑）");
                script.AppendLine($"                  transformedPath = transformedPath.replace(/([MLHVCSQTAZ])([^MLHVCSQTAZ]*)/gi, function(match, command, coords) {{");
                script.AppendLine($"                    if (!coords || coords.trim() === '') return command;");
                script.AppendLine($"                    ");
                script.AppendLine($"                    const numbers = coords.match(/-?\\d+(?:\\.\\d+)?/g);");
                script.AppendLine($"                    if (!numbers) return match;");
                script.AppendLine($"                    ");
                script.AppendLine($"                    const transformedNumbers = [];");
                script.AppendLine($"                    const upperCommand = command.toUpperCase();");
                script.AppendLine($"                    ");
                script.AppendLine($"                    switch (upperCommand) {{");
                script.AppendLine($"                      case 'M': // MoveTo");
                script.AppendLine($"                      case 'L': // LineTo");
                script.AppendLine($"                        for (let i = 0; i < numbers.length; i += 2) {{");
                script.AppendLine($"                          if (i + 1 < numbers.length) {{");
                script.AppendLine($"                            const x = parseFloat(numbers[i]) * scaleX + translateX;");
                script.AppendLine($"                            const y = parseFloat(numbers[i + 1]) * scaleY + translateY;");
                script.AppendLine($"                            transformedNumbers.push(x, y);");
                script.AppendLine($"                          }}");
                script.AppendLine($"                        }}");
                script.AppendLine($"                        break;");
                script.AppendLine($"                      case 'H': // Horizontal LineTo");
                script.AppendLine($"                        for (let i = 0; i < numbers.length; i++) {{");
                script.AppendLine($"                          const x = parseFloat(numbers[i]) * scaleX + translateX;");
                script.AppendLine($"                          transformedNumbers.push(x);");
                script.AppendLine($"                        }}");
                script.AppendLine($"                        break;");
                script.AppendLine($"                      case 'V': // Vertical LineTo");
                script.AppendLine($"                        for (let i = 0; i < numbers.length; i++) {{");
                script.AppendLine($"                          const y = parseFloat(numbers[i]) * scaleY + translateY;");
                script.AppendLine($"                          transformedNumbers.push(y);");
                script.AppendLine($"                        }}");
                script.AppendLine($"                        break;");
                script.AppendLine($"                      case 'C': // CurveTo");
                script.AppendLine($"                        for (let i = 0; i < numbers.length; i += 6) {{");
                script.AppendLine($"                          if (i + 5 < numbers.length) {{");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i]) * scaleX + translateX);     // x1");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 1]) * scaleY + translateY); // y1");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 2]) * scaleX + translateX); // x2");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 3]) * scaleY + translateY); // y2");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 4]) * scaleX + translateX); // x");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 5]) * scaleY + translateY); // y");
                script.AppendLine($"                          }}");
                script.AppendLine($"                        }}");
                script.AppendLine($"                        break;");
                script.AppendLine($"                      case 'Q': // QuadraticCurveTo");
                script.AppendLine($"                        for (let i = 0; i < numbers.length; i += 4) {{");
                script.AppendLine($"                          if (i + 3 < numbers.length) {{");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i]) * scaleX + translateX);     // x1");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 1]) * scaleY + translateY); // y1");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 2]) * scaleX + translateX); // x");
                script.AppendLine($"                            transformedNumbers.push(parseFloat(numbers[i + 3]) * scaleY + translateY); // y");
                script.AppendLine($"                          }}");
                script.AppendLine($"                        }}");
                script.AppendLine($"                        break;");
                script.AppendLine($"                      case 'Z': // ClosePath");
                script.AppendLine($"                        return command;");
                script.AppendLine($"                      default:");
                script.AppendLine($"                        // 对于其他命令，简单地应用变换");
                script.AppendLine($"                        for (let i = 0; i < numbers.length; i += 2) {{");
                script.AppendLine($"                          if (i + 1 < numbers.length) {{");
                script.AppendLine($"                            const x = parseFloat(numbers[i]) * scaleX + translateX;");
                script.AppendLine($"                            const y = parseFloat(numbers[i + 1]) * scaleY + translateY;");
                script.AppendLine($"                            transformedNumbers.push(x, y);");
                script.AppendLine($"                          }}");
                script.AppendLine($"                        }}");
                script.AppendLine($"                        break;");
                script.AppendLine($"                    }}");
                script.AppendLine($"                    ");
                script.AppendLine($"                    return command + transformedNumbers.join(',');");
                script.AppendLine($"                  }});");
                script.AppendLine($"                  ");
                script.AppendLine($"                  // 将变换后的路径添加到pathData中");
                script.AppendLine($"                  pathData{index} += ' ' + transformedPath;");
                script.AppendLine($"                  console.log('应用变换后的路径:', transformedPath);");
                script.AppendLine($"                }}");
                script.AppendLine($"              }});");
                script.AppendLine($"            }}");
                script.AppendLine($"          }}");
                script.AppendLine($"        }}");
                script.AppendLine($"      }});");
                script.AppendLine($"    }}");
                script.AppendLine($"    ");
                script.AppendLine($"    const widthMatch{index} = svgContent{index}.match(/width\\s*=\\s*[\"']([^\"']*)[\"']/i);");
                script.AppendLine($"    const width{index} = widthMatch{index} ? parseInt(widthMatch{index}[1]) : 1000;");
                script.AppendLine($"    svgFont += `<glyph unicode=\"&#x{unicode:X};\" horiz-adv-x=\"${{width{index}}}\" d=\"${{pathData{index}}}\" />\\n`;");
                script.AppendLine($"    console.log('添加字形: {fileName} (U+{unicode:X}), 宽度:', width{index});");
                script.AppendLine("  }");
                script.AppendLine();
                unicode++;
                index++;
            }
            
            script.AppendLine("  svgFont += '</font>\\n';");
            script.AppendLine("  svgFont += '</defs>\\n';");
            script.AppendLine("  svgFont += '</svg>';");
            script.AppendLine();
            script.AppendLine("  console.log('SVG字体创建完成，开始转换为TTF...');");
            script.AppendLine();
            script.AppendLine("  // 转换为TTF");
            script.AppendLine("  const ttf = svg2ttf(svgFont, {});");
            script.AppendLine($"  fs.writeFileSync('{outputPath.Replace("\\", "/")}', Buffer.from(ttf.buffer));");
            script.AppendLine();
            script.AppendLine($"  console.log('TTF字体转换成功: {outputPath}');");
            script.AppendLine("} catch (error) {");
            script.AppendLine("  console.error('SVG2TTF转换失败:', error.message);");
            script.AppendLine("  process.exit(1);");
            script.AppendLine("}");
            
            return script.ToString();
        }
    }
}